﻿using Common.Logging;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.DirectoryServices;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Wicresoft.EKA.NRemedy;

namespace Wicresoft.Task.EmployeeSync
{
    class FullPeopleInfo : IFullPeopleInfo
    {
        private static readonly string LdapPath = ConfigurationManager.AppSettings["LDAP"];
        private static readonly string LdapUser = ConfigurationManager.AppSettings["LDAPUser"];
        private static readonly string LdapPwd = ConfigurationManager.AppSettings["LDAPPwd"];
        private static readonly ILog logger = LogManager.GetCurrentClassLogger();
        private ARLoginContext context = null;
        private ARProxy<CTMPeopleModel> proxy = null;

        public FullPeopleInfo(ARLoginContext context)
        {
            this.context = context;
            this.proxy = new ARProxy<CTMPeopleModel>(context);
        }

        public IList<CTMPeopleModel> GetDestinationList()
        {
            IList<CTMPeopleModel> destinationList =null;
                
            try
            {
                destinationList= proxy.GetListEntry("'" + CTMPeopleModel.EmployeeNumber_ID + "'!=$NULL$", new List<uint>() 
                {
                    CTMPeopleModel.FirstName_ID,
                    CTMPeopleModel.LastName_ID,
                    CTMPeopleModel.FullName_ID,
                    CTMPeopleModel.ProfileStatus_ID,
                    CTMPeopleModel.RemedyLoginID_ID,
                    CTMPeopleModel.Organization_ID,
                    CTMPeopleModel.Department_ID,
                    CTMPeopleModel.InternetEmail_ID,
                    CTMPeopleModel.PhoneNumberBusiness_ID,
                    CTMPeopleModel.EmployeeNumber_ID,
                    CTMPeopleModel.JobTitle_ID
                });
            }
            catch (Exception ex)
            {
                logger.Error("Get Destination List Error:"+ex);
            }
            return destinationList;
        }


        //TODO 提取为Virtual 方法。
        public IList<CTMPeopleModel> GetSourceList()
        {
            var listPeople = new List<CTMPeopleModel>();
            //var Path = "LDAP://10.230.12.3:389/OU=IT服务部_165787,OU=信息技术中心_253,OU=企业发展办公室_59634,OU=总裁_104,OU=全公司_103,OU=用户,OU=德邦物流,DC=deppon,DC=com";
            //var Username = "ldaptest";
            //var Password = "P@ssw0rd";
            try
            {
                using (var de = new DirectoryEntry(LdapPath, LdapUser, LdapPwd, AuthenticationTypes.None))
                {
                    GetUserFromLdap(de, listPeople);
                }
            }
            catch (COMException ex)
            {
                logger.Error("Get Source List Error:"+ex);
            }

            return listPeople;
        }

        public void GetUserFromLdap(DirectoryEntry de, List<CTMPeopleModel> listPeople)
        {
            de.Children.SchemaFilter.Clear();
            de.Children.SchemaFilter.Add("user");
            foreach (DirectoryEntry obj in de.Children)
            {
                listPeople.Add(ADHelper.ConvertFromDirectory(obj, logger));
            }
            de.Children.SchemaFilter.Clear();
            de.Children.SchemaFilter.Add("organizationalUnit");
            foreach (DirectoryEntry obj in de.Children)
            {
                GetUserFromLdap(obj, listPeople);
            }
        }

        public void HandlerPeople(CTMPeopleModel source, CTMPeopleModel destination)
        {
            throw new NotImplementedException();
        }

        public bool IsFull
        {
            get { return true; }
        }


        public bool Equals(CTMPeopleModel source, CTMPeopleModel destination)
        {
            throw new NotImplementedException();
        }

        public void HandlerAll()
        {

            var listSource = GetSourceList();
            var listDistincation = GetDestinationList();

            PropertyInfo _keyPropertyInfo = null;

            foreach (PropertyInfo item in typeof(CTMPeopleModel).GetProperties())
            {
                if (item.GetCustomAttributes(false).Count(a => a is ArithmeticKeyAttribute) != 0)
                {
                    _keyPropertyInfo = item;
                }
            }

            ArithmeticHelper<CTMPeopleModel>.Traverse(listSource, listDistincation, this.Create, this.Modify, this.Delete, _keyPropertyInfo);


        }



        public void Create(CTMPeopleModel source)
        {
            try
            {
                if (source.ProfileStatus == CTMPeopleModel.ProfileStatus_Enum.Enabled && !string.IsNullOrWhiteSpace(source.RemedyLoginID))
                {
                    source.LastName = source.FullName.Substring(0, 1);
                    source.FirstName = source.FullName.Substring(1);
                    source.Organization = "IT服务部";
                    source.Company = "德邦物流股份有限公司";
                    source.ClientType = Wicresoft.Task.EmployeeSync.CTMPeopleModel.ClientType_Enum.OfficeBasedEmployee;
                    source.Site = "上海市青浦区徐泾镇明珠路徐祥路";
                    source.SiteID = "STE000000003327";
                    source.z1DPassword = source.EmployeeNumber;
                    proxy.CreateEntry(source);
                    logger.Info("Create People 【" + source.EmployeeNumber + "】");
                }
            }
            catch (Exception ex)
            {
                logger.Error("Create People Error【"+source.EmployeeNumber+"】"+ex);
            }
        }

        public void Modify(CTMPeopleModel source, CTMPeopleModel destination)
        {
            try
            {
                if (source.ProfileStatus == CTMPeopleModel.ProfileStatus_Enum.Delete)
                {
                    Delete(destination);
                }
                else
                {
                    if (source.Department != destination.Department ||
                        source.FullName != destination.FullName ||
                        source.InternetEmail != destination.InternetEmail ||
                        source.PhoneNumberBusiness != destination.PhoneNumberBusiness ||
                        source.JobTitle != destination.JobTitle
                        )
                    {
                        if (source.RemedyLoginID != destination.RemedyLoginID) throw new InvalidOperationException("Can not change the login ID");
                        source.PersonID = destination.PersonID;
                        proxy.SetEntry(source);
                        logger.Info("Modify People 【" + source.EmployeeNumber + "】");
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("Modify Prople Error:【"+source.EmployeeNumber+"】"+ex);
            }
        }

        public void Delete(CTMPeopleModel detination)
        {
            try
            {
                detination.ProfileStatus = CTMPeopleModel.ProfileStatus_Enum.Delete;
                proxy.SetEntry(detination);
                //proxy.DeleteEntry(detination);
                logger.Info("Delete People 【" + detination.EmployeeNumber + "】");
            }
            catch (Exception ex)
            {
                logger.Error("delete people error:【"+detination.EmployeeNumber+"】"+ex);
            }
        }
    }
}
